package cn.iotnc.camera.ui.display

import android.app.Application
import androidx.lifecycle.MutableLiveData
import cn.iotnc.camera.api.CameraApi
import cn.iotnc.camera.api.CameraApi.Companion.toBaseUrl
import cn.iotnc.camera.base.BaseViewModel
import cn.iotnc.camera.model.PictureBody
import dagger.hilt.android.lifecycle.HiltViewModel
import retrofit2.Retrofit
import retrofit2.create
import java.io.InputStream
import javax.inject.Inject

@HiltViewModel
class DisplayViewModel @Inject constructor(
    app: Application,
    private val retrofit: Retrofit
) : BaseViewModel(app) {

    private val api by lazy { retrofit.create<CameraApi>() }
    val pictureData = MutableLiveData<Result<InputStream>>()

    fun getPicture(ip: String) = launchNotNull(
        block = {
            api.getPicture(ip.toBaseUrl(), PictureBody())
        },
        success = {
            pictureData.postValue(Result.success(it.byteStream()))
        },
        error = {
            pictureData.postValue(Result.failure(it))
        }
    )
}